package com.autodesk.akn.emr;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.autodesk.akn.emr.services.EMRService;
import com.autodesk.akn.emr.services.S3Service;

/**
 *
 */
public class MainApp
{
	private static final Logger LOGGER = Logger.getLogger(MainApp.class.getName());
	
	@Autowired
	S3Service s3Service;

	@Autowired
	EMRService emrService;

	public S3Service getS3Service() {
		return s3Service;
	}

	public void setS3Service(S3Service s3Service) {
		this.s3Service = s3Service;
	}

	public EMRService getEmrService() {
		return emrService;
	}

	public void setEmrService(EMRService emrService) {
		this.emrService = emrService;
	}

    public void runMainFlow() throws InterruptedException {
    	List<String> files = s3Service.getLogPaths();
    	for (String file : files) {
    		LOGGER.info(" PROCESSING FILE: " + file);
	        String jobID = emrService.processLogFiles(file);
	        if (jobID != null && !jobID.isEmpty()) {
	        	LOGGER.info("JOB ID : " + jobID);
	        	Thread.sleep(10000);
	        	String jobStatus = emrService.jobStatus(jobID);
	        	while ("running".equals(jobStatus.toLowerCase())
	        			|| "bootstrapping".equals(jobStatus.toLowerCase())
	        			|| "starting".equals(jobStatus.toLowerCase())
	        			|| "shutting_down".equals(jobStatus.toLowerCase())) {
	        		jobStatus = emrService.jobStatus(jobID);
	        		LOGGER.info("STATUS: "+jobStatus+" - Wait 10 seconds until job is completed...");
	        		Thread.sleep(10000);
	    		}
	        	LOGGER.info("STATUS: "+jobStatus);
	        	if ("completed".equals(jobStatus.toLowerCase())) {
	        		LOGGER.info("JOB COMPLETED SUCCESSFULLY. IMPORTING TO DATABASE");
	        		s3Service.dbLoaderProcess(file);
	        		LOGGER.info("DATA IMPORTED SUCCESSFULLY");
	        	}
	        	
	        	if ("failed".equals(jobStatus.toLowerCase())) {
	        		LOGGER.info("JOB FAILED. PLEASE CHECK LOGS");
	        	}
	        }
	        LOGGER.info("END PROCESSING FILE: " + file);
    	}
    }

	public static void main( String[] args )
    {
    	try {
    	  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
	          new String[] { "application-context.xml" });
	      LOGGER.info("Starting main flow");
	      MainApp mainApp = (MainApp) context.getBean("mainApp");
	      mainApp.runMainFlow();
    	} catch (Exception e) {
    		throw new RuntimeException("Error on main app: " + e.getMessage());
    	}
    }
}
